# -*- coding: utf-8 -*-
# time: 2025/8/9 16:17
# file: serializers.py
# author: kai
# email: 1071664616@qq.com

"""
健康信息序列化
"""
from rest_framework import serializers

from .models import BodyRecord, Comment, EatingRecord, Notice, SleepRecord, SportsRecord, ScheduledTask, HealthNews, \
    SensitiveWord, Post, PostLike, PostFavorite, HealthReport
from ..users.models import User


class BodyRecordSerializer(serializers.ModelSerializer):
    bmi = serializers.SerializerMethodField()
    
    class Meta:
        model = BodyRecord
        fields = '__all__'
    
    def get_bmi(self, obj):
        return obj.bmi


class BodyRecordCreateSerializer(serializers.ModelSerializer):
    bmi = serializers.SerializerMethodField()
    
    class Meta:
        model = BodyRecord
        fields = '__all__'
        read_only_fields = ['bmi']

    def get_bmi(self, obj):
        return obj.bmi

    def validate_user_id(self, value):
        request = self.context.get('request')
        if request and not request.user.is_admin() and request.user.id != value:
            raise serializers.ValidationError("您只能为自己创建身体指标记录")
        return value

class CommentSerializer(serializers.ModelSerializer):
    user_nickname = serializers.SerializerMethodField()
    
    class Meta:
        model = Comment
        fields =  [
            'id', 'user_nickname', 'content',
            'pid', 'comment_time', 'fid', 'module',
            'root_id', 'created_at'
        ]
    
    def get_user_nickname(self, obj):
        # 当没有外键关系时，通过 user_id 查询用户信息
        if obj.user_id:
            print(f"检测到用户信息: user_id = {obj.user_id}")
            try:
                user = User.objects.get(id=obj.user_id)
                return getattr(user, 'username', '匿名用户')
            except User.DoesNotExist:
                return '匿名用户'
        return '匿名用户'

class CommentCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = '__all__'
        read_only_fields = ['user_id']  # 将 user_id 设为只读

    def create(self, validated_data):
        # 从请求上下文中获取当前用户
        request = self.context.get('request')
        if request and hasattr(request, 'user'):
            validated_data['user_id'] = request.user.id
        return super().create(validated_data)
        
    def validate_content(self, value):
        """
        验证评论内容是否包含敏感词
        """
        try:
            from django.apps import apps
            # 获取服务应用的配置
            checker_module = apps.get_app_config('backend').module
            # 动态导入checker模块
            import importlib.util
            import os
            checker_path = os.path.join(os.path.dirname(checker_module.__file__), 'services', 'checker.py')
            spec = importlib.util.spec_from_file_location("checker", checker_path)
            checker = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(checker)
            
            SensitiveDetector = getattr(checker, 'SensitiveDetector')
            detector = SensitiveDetector()
            detector.initialize()
            result = detector.detect(value)
            
            if result.is_sensitive:
                # 收集所有敏感词
                sensitive_words = [word.word for word in result.sensitive_words]
                raise serializers.ValidationError(f"评论内容包含敏感词: {', '.join(sensitive_words)}")
        except Exception as e:
            # 如果敏感词检测服务不可用，则跳过检测
            pass
        return value


class PostSerializer(serializers.ModelSerializer):
    """
    帖子序列化器
    """
    user_nickname = serializers.SerializerMethodField()
    user_avatar = serializers.SerializerMethodField()  # 添加用户头像字段
    comments_count = serializers.SerializerMethodField()
    status_display = serializers.SerializerMethodField()  # 添加状态显示字段
    
    class Meta:
        model = Post
        fields = ['id', 'title', 'content', 'user_id', 'user_nickname', 'user_avatar', 'comments_count', 'status', 'status_display', 'created_at', 'updated_at']
        read_only_fields = ['user_id', 'created_at', 'updated_at']

    def get_user_nickname(self, obj):
        # 添加调试信息
        print(f"查询用户信息: post.user_id = {obj.user_id}")
        try:
            user = User.objects.get(id=obj.user_id)
            print(f"找到用户: {user.username}")
            return user.username
        except User.DoesNotExist:
            print(f"用户不存在: user_id = {obj.user_id}")
            return "未知用户"
        except Exception as e:
            print(f"查询用户时出错: {e}")
            return "匿名用户"

    def get_user_avatar(self, obj):
        """获取用户头像URL"""
        try:
            user = User.objects.get(id=obj.user_id)
            if user.avatar:
                return user.avatar.url
            return None
        except User.DoesNotExist:
            return None
        except Exception:
            return None

    def get_comments_count(self, obj):
        return Comment.objects.filter(fid=obj.id, module='post').count()
        
    def get_status_display(self, obj):
        """获取状态的显示文本"""
        return obj.get_status_display()

class PostCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ['title', 'content', 'status']  # 添加status字段

    def create(self, validated_data):
        # 从上下文中获取用户，但不要在这里设置user_id
        # 让perform_create方法处理user_id的设置
        return super().create(validated_data)

class EatingRecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = EatingRecord
        fields = '__all__'


class EatingRecordCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = EatingRecord
        fields = '__all__'

    def create(self, validated_data):
        # 从请求上下文中获取当前用户
        request = self.context.get('request')
        if request and hasattr(request, 'user'):
            validated_data['user_id'] = request.user.id
        return super().create(validated_data)

    def validate_user_id(self, value):
        request = self.context.get('request')
        if request and not request.user.is_admin() and request.user.id != value:
            raise serializers.ValidationError("您只能为自己创建饮食记录")
        return value

class NoticeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Notice
        fields = '__all__'

class SleepRecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = SleepRecord
        fields = '__all__'


class SleepRecordCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = SleepRecord
        fields = '__all__'

    def create(self, validated_data):
        # 从请求上下文中获取当前用户
        request = self.context.get('request')
        if request and hasattr(request, 'user'):
            validated_data['user_id'] = request.user.id
        return super().create(validated_data)

    def validate_user_id(self, value):
        request = self.context.get('request')
        if request and not request.user.is_admin() and request.user.id != value:
            raise serializers.ValidationError("您只能为自己创建睡眠记录")
        return value

class SportsRecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = SportsRecord
        fields = '__all__'


class SportsRecordCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = SportsRecord
        fields = '__all__'

    def create(self, validated_data):
        # 从请求上下文中获取当前用户
        request = self.context.get('request')
        if request and hasattr(request, 'user'):
            validated_data['user_id'] = request.user.id
        return super().create(validated_data)

    def validate_user_id(self, value):
        request = self.context.get('request')
        if request and not request.user.is_admin() and request.user.id != value:
            raise serializers.ValidationError("您只能为自己创建运动记录")


class ScheduledTaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = ScheduledTask
        fields = '__all__'
        read_only_fields = ['last_run', 'created_at', 'updated_at']


class HealthNewsSerializer(serializers.ModelSerializer):
    """
    健康资讯序列化器
    """
    class Meta:
        model = HealthNews
        fields = '__all__'

class SensitiveWordSerializer(serializers.ModelSerializer):
    """
    敏感词序列化器
    """
    level_display = serializers.SerializerMethodField()  # 添加级别显示字段
    
    class Meta:
        model = SensitiveWord
        fields = '__all__'
        read_only_fields = ['created_at', 'updated_at']

    def get_level_display(self, obj):
        """获取级别的显示文本"""
        return obj.get_level_display()

class SensitiveWordCreateSerializer(serializers.ModelSerializer):
    """
    敏感词创建序列化器
    """
    class Meta:
        model = SensitiveWord
        fields = ['word', 'category', 'level']


class PostFavoriteSerializer(serializers.ModelSerializer):
    """
    帖子收藏序列化器
    """
    post_title = serializers.SerializerMethodField()
    post_user_nickname = serializers.SerializerMethodField()
    
    class Meta:
        model = PostFavorite
        fields = ['id', 'post', 'post_title', 'post_user_nickname', 'created_at']
        read_only_fields = ['created_at']

    def get_post_title(self, obj):
        return obj.post.title

    def get_post_user_nickname(self, obj):
        try:
            from ..users.models import User
            user = User.objects.get(id=obj.post.user_id)
            return user.username
        except User.DoesNotExist:
            return "未知用户"


class PostLikeSerializer(serializers.ModelSerializer):
    """
    帖子点赞/踩序列化器
    """
    class Meta:
        model = PostLike
        fields = ['id', 'post', 'like_type', 'created_at']
        read_only_fields = ['created_at']


class HealthReportSerializer(serializers.ModelSerializer):
    """
    体检报告序列化器
    """
    status_display = serializers.SerializerMethodField()
    
    class Meta:
        model = HealthReport
        fields = '__all__'
        read_only_fields = ['user_id', 'uploaded_at', 'analysis_result', 'status']
    
    def get_status_display(self, obj):
        """获取状态的显示文本"""
        return obj.get_status_display()

class HealthReportCreateSerializer(serializers.ModelSerializer):
    """
    体检报告创建序列化器
    """
    class Meta:
        model = HealthReport
        fields = ['file_path']

    def create(self, validated_data):
        # 从请求上下文中获取当前用户
        request = self.context.get('request')
        if request and hasattr(request, 'user'):
            validated_data['user_id'] = request.user.id
        return super().create(validated_data)
